Clean Architecture is a software design pattern that promotes separation of concerns, testability, and maintainability. It structures an application into layers, ensuring dependencies flow inwards (towards business logic) and that the core logic is independent of frameworks and external dependencies.
Clean Architecture consists of four main layers:
public class Product
{
public int Id { get; private set; }
public string Name { get; private set; }
public decimal Price { get; private set; }
public Product(string name, decimal price)
{
Name = name;
Price = price;
}
}
public class CreateProductCommand
{
public string Name { get; set; }
public decimal Price { get; set; }
}
public class ProductService
{
private readonly IProductRepository _productRepository;
public ProductService(IProductRepository productRepository)
{
_productRepository = productRepository;
}
public async Task<int> CreateProduct(CreateProductCommand command)
{
var product = new Product(command.Name, command.Price);
await _productRepository.AddAsync(product);
return product.Id;
}
}
public class ProductRepository : IProductRepository
{
private readonly ApplicationDbContext _context;
public ProductRepository(ApplicationDbContext context)
{
_context = context;
}
public async Task AddAsync(Product product)
{
_context.Products.Add(product);
await _context.SaveChangesAsync();
}
}
[ApiController]
[Route("api/products")]
public class ProductController : ControllerBase
{
private readonly ProductService _productService;
public ProductController(ProductService productService)
{
_productService = productService;
}
[HttpPost]
public async Task<IActionResult> CreateProduct([FromBody] CreateProductCommand command)
{
var productId = await _productService.CreateProduct(command);
return CreatedAtAction(nameof(CreateProduct), new { id = productId });
}
}
This ensures the business logic is central and not coupled to frameworks, databases, or UI.
/src
/Domain
/Entities
/ValueObjects
/DomainServices
/Application
/Interfaces
/Services
/DTOs
/UseCases
/Infrastructure
/Persistence
/Repositories
/ExternalServices
/Presentation
/Controllers
/Views (if MVC)
/ReactApp (if using React)
📂 MyApp.sln (Solution file)
MyApp.WebAPI
)📂 MyApp.WebAPI
MyApp.Application
)📂 MyApp.Application
IUserService
, IOrderService
, etc.IUserService
, IOrderService
, etc.MyApp.Domain
)📂 MyApp.Domain
MyApp.Infrastructure
)📂 MyApp.Infrastructure
IRepository<TEntity>
for data access.MyApp.Tests
– Unit and integration tests.MyApp.Shared
– Shared utilities (cross-cutting concerns like constants, helpers).